import _ from 'lodash';
import DB from '../util/db';
import dbcfg from '../../etc/db';
import cfg from '../../etc/cfg';

const lang = cfg.lang;
const db = new DB(dbcfg);
export default db;


db.set('role', {id: 'Id'});

db.set('user', {id: 'Id'});

db.set('action', {id: 'Id'});

db.set('department', {id: 'Id'});

db.set('module', {id: 'Id'});

db.set('patInfoBasic', {id: 'Id'});

db.set('printtemplate', {id: 'Id'});

db.set('visit', {id: 'Id'});

db.set('v_visit', {id: 'Id'});

db.set('workstation', {id: 'Id'});

db.set('dict', {id: 'Id'});

db.set('dic_mr_element',
    {id: 'code'}
);
db.set('dic_mr_element_value',
    {id: 'id'}
);

db.set('dic_mr_segement_class',
    {
        id: 'code',
        segTypes: function a() {
            return this.hasMany(db.get('dic_mr_segement'), ['class_code'])
                .query(qb => qb.where({
                    language: lang
                }));
        }
    }
);
db.set('dic_mr_segement',
    {
        id: 'code',
        elements: function a() {
            return this.hasMany(db.get('dic_mr_element'), 'segement_type_code').through(db.get('dic_mr_segement_element'), 'code')
                .query(qb => qb.where({
                    language: lang
                }));
        }
    }
);
db.set('dic_mr_segement_element',
    {
        id: 'element_type_code',
        elementValues: function aa() {
            return this.hasMany(db.get('dic_mr_element_value'), ['element_type_code'])
                .query(qb => qb.where({
                    language: lang
                }));
        }
    }
);
export const AND = ' AND ';
export const NOT = ' NOT ';

export const _count = res => _.sumBy(res, x => x.count || 0);

const whereMethods = 'where,andWhere,orWhere,whereNot,orWhereNot,whereIn,orWhereIn,whereNotIn,orWhereNotIn,whereNotNull,orWhereNotNull,whereBetween,orWhereBetween,whereNotBetween,orWhereNotBetween'.split(',');//,whereExists

//[{where:[]},{whereIn:[]}]

/**
 * 是否是高级where查询对象
 * @param arr
 * @returns {boolean}
 */
const isWhereMixed = (obj) => _.isPlainObject(obj) && _.every(_.keys(obj), k => _.includes(whereMethods, k));

function whereMixed(qb, arr) {
    arr = _.castArray(arr);
    _.each(arr, whs => {
        if (isWhereMixed(whs)) {
            _.each(whs,
                (v, k) => {
                    if (isWhereMixed(v)) {
                        qb[k](qb2 => whereMixed(qb2, v));
                    } else {
                        if (!_.includes(whereMethods, k)) {
                            throw `where高级查询中出现未知操作方法:${k}`;
                        }
                        v = _.castArray(v);
                        qb[k](...v);
                    }
                }
            );
        } else {
            qb.where(whs);
        }
    });
}

/**
 * 获取查询条件
 * @param query
 * @param filters 字段过滤
 * @param cb  字段过滤或者结果处理(k===undefined)
 * @returns {*}
 */
export const where = (model, query, filters = 'pageSize,page,_fs,_where', cb) => {
    let whereQuery = query._where && JSON.parse(query._where);
    if (whereQuery) {
        whereQuery = cb === undefined ? whereQuery : cb(whereQuery);
        return model.query(qb => whereMixed(qb, whereQuery));
    }
    if (filters) {
        if (_.isString(filters)) {
            filters = filters.split(',');
        } else if (_.isFunction(filters)) {
            cb = filters;
            filters = undefined;
        }
    }
    let res = _.reduce(query, (res, v, k) => {
        if (!filters || !_.includes(filters, k)) {
            if (cb === undefined || !cb(res, k)) {
                res[k] = v;
            }
        }
        return res;
    }, {});
    res = cb === undefined ? res : cb(res);
    return model.where(res);
};

/**
 * model更新，新建
 * @param model
 */
export const createSave = (model) => (data, method) => {
    if (method) {
        return new model(data).save();
    }
    const id = data.Id;
    delete data.Id;
    return model.where({Id: id}).save(data, {
        method: 'update'
    });
};

